import 'dart:convert';

import 'package:cher_flare/config/config.dart';
import 'package:cher_flare/modules/login/models/ly_login_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../common/models/ly_image_model.dart';

class LYLoginInfoManager {
  static final LYLoginInfoManager _instance = LYLoginInfoManager._internal();
  LYLoginInfoManager._internal();
  static LYLoginInfoManager get getInstance => _instance;

  LyLoginModel? loginModel;

  Future<void> saveLoginInfo(dynamic json) async {
    final pres = await SharedPreferences.getInstance();
    pres.setString("login_info", jsonEncode(json));
    pres.setBool("isLogin", true);
    loginModel = LyLoginModel.fromJson(json);
    return;
  }

  Future<bool> getLoginInfo() async {
    final pres = await SharedPreferences.getInstance();
    final res = pres.getString("login_info");
    if (res != null) {
      loginModel = LyLoginModel.fromJson(jsonDecode(res));
    }
    return loginModel != null;
  }

  void updateUserInfo(UserInfo userInfo) async {
    loginModel?.userInfo = userInfo;
    final json = loginModel?.toJson();
    if (json != null) {
      final pres = await SharedPreferences.getInstance();
      pres.setString("login_info", jsonEncode(json));
    }
  }

  void updateAvatarInfo(LyImageModel model) async {
    loginModel?.userInfo?.avatar = model.mediaPath;
    loginModel?.userInfo?.avatarUrl = model.mediaUrl;
    loginModel?.userInfo?.avatarMiddleThumbUrl = model.middleThumbUrl;
    loginModel?.userInfo?.avatarThumbUrl = model.thumbUrl;
    final json = loginModel?.toJson();
    if (json != null) {
      final pres = await SharedPreferences.getInstance();
      pres.setString("login_info", jsonEncode(json));
    }
  }

  void logout() async {
    final pres = await SharedPreferences.getInstance();
    pres.remove("login_info");
    pres.setBool("isLogin", false);
    Config.isLogin = false;
  }
}
